<template>
  <div class="dispose_course">
    <el-dialog :title="isDispose ? '销课' : '撤销销课'" :visible.sync="visible" @close="handleCancel">
      <div v-if="studentInfo.expiresStartTime || studentInfo.expiresInfo == '不限期'">
        <el-row v-if="studentInfo.isShowDispose">
          <el-col :span="4">次课课程：</el-col>
          <el-col :span="20" v-if="train_student_dispose_list.length">
            <el-select v-model="selectedList" @change="handleSelected" placeholder="请选择次课课程" style="width: 80%;" size="small">
              <el-option v-for="(item, index) in train_student_dispose_list" :key="index" :value="{schoolId: item.schoolId, studentSignupId: item.signupId}" :label="`${item.schoolName}-${item.classesName}-${item.courseName}`">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="20" v-else>
            无次课课程
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              {{isDispose ? '请选择销课课时（注：只能选择有效期范围内的课时）：' : '请选择要撤销的销课：'}}
            </div>
          </el-col>
        </el-row>
        <el-row v-if="isDispose">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-date-picker 
                v-model="dateMonth" 
                type="month" 
                format="yyyy 年 MM 月" 
                :clearable="false" 
                :picker-options="studentInfo.expiresInfo.includes('不限期') ? '' : pickerOptions"
                @change="selectedMonth"></el-date-picker>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-light" v-if="isDispose">
              <div v-if="unDisposeList.length">
                <el-scrollbar class="import_table" wrap-class="vacade-scroll">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="(item, index) in unDisposeList" :key="index" :label="item" :disabled="item.status != 0">
                      <span>{{new Date(item.beginClassDate).format('yyyy-MM-dd')}} {{item.weekCode | getWeekDay}} {{new Date(item.beginTime).format('hh:mm')}}-{{new Date(item.endTime).format('hh:mm')}}</span><span> {{item.teacherName}}（{{item.statusDesc}}）</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </el-scrollbar>
              </div>
              <div v-else style="text-indent: 20px; margin-top: 10px;">
                <span>{{studentInfo.isClassDispose && classData.classCycle.length ? '暂无可销课时' : studentInfo.isClassDispose && studentInfo.usedTimes == 0 ? '该班级还未设置上课周期，请先设置' : isSelected && unDisposeList.length == 0 ? '暂无销课课时' : studentInfo.isShowDispose ? '请先选择次课课程' : '无销课课时'}}</span>
                <!-- <span>{{studentInfo.isClassDispose && classData.classCycle.length ? '暂无可销课时' : studentInfo.isClassDispose && studentInfo.usedTimes == 0 ? '还未设置上课周期，暂无可销课时' : isSelected && unDisposeList.length == 0 ? '无销课课时' : studentInfo.isShowDispose ? '请先选择次课课程' : '无销课课时'}}</span> -->
              </div>
            </div>
            <div class="grid-content bg-purple-light" v-else>
              <div v-if="disposeList.length">
                <el-scrollbar class="import_table" wrap-class="vacade-scroll">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="(item, index) in disposeList" :key="index" :label="item.id" :disabled="item.comment">
                      <span>{{new Date(item.beginDate).format('yyyy-MM-dd')}} {{item.beginWeekCode | getWeekDay}} {{new Date(item.startTime).format('hh:mm')}}-{{new Date(item.endTime).format('hh:mm')}}</span>
                      <span class="operator" :title="item.signinerName">销课人：{{item.signinerName}}</span>
                      <span v-if="item.scheduleType == 1">(赠课)</span>
                      <span v-if="item.comment">(已点评，不可撤销)</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </el-scrollbar>
              </div>
              <div v-else style="text-indent: 20px;">
                <span>{{studentInfo.isClassDispose ? '暂无可撤销的课时' : '请先选择次课课程'}}</span>              
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="selectedNum" v-if="(isDispose && unDisposeList.length) || (!isDispose && disposeList.length)">已选数量： {{checkList.length}}</div>
      </div>
      <div v-else class="expiration_date">
        {{studentInfo.expiresStartTime ? '未到有效期，不能进行销课操作' : '请先设置有效期'}}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :disabled="checkList.length == 0" :loading="loading">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import api from 'api/train'
export default {
  props: {
    isDispose: { // 销课 true 撤销销课 false
      type: Boolean,
      default: true
    },
    studentInfo: {
      type: Object
    },
    isStudentDispose: {
      type: Boolean,
      default: false
    },
    classData: {
      type: Object
    },
    isDisposeType: { // 销课类型（0-正常课，1-增课）
      default: 0
    }
  },
  data () {
    let endValid = this.studentInfo.expiresEndTime
    let startValid = this.studentInfo.expiresStartTime
    return {
      visible: true,
      loading: false,
      checkList: [],
      selectedList: '',
      isSelected: false,
      unDisposeList: [],
      disposeList: [],
      dateMonth: new Date(),
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > endValid || time.getTime() < startValid
        }
      }
    }
  },
  computed: {
    ...mapGetters({
      train_student_dispose_list: 'train_student_dispose_list'
    })
  },
  mounted () {
    if (this.studentInfo.isShowDispose) { // 学员入口
      this.$store.dispatch('train_student_dispose_list', {studentId: this.studentInfo.id})
    } else if ((this.studentInfo.isClassDispose && this.studentInfo.expiresEndTime) || this.studentInfo.expiresInfo.includes('不限期')) {
      this.handleTimeParams(this.dateMonth) // 班级入口
    }
  },
  methods: {
    handleCancel () {
      this.$emit('input', false)
    },
    selectedMonth (value) {
      // console.log(value, new Date().setYear(value.split('年')[0]), value.split('年')[1].split('月')[0] - 1, new Date(new Date(new Date().setYear(value.split('年')[0])).setMonth(value.split('年')[1].split('月')[0] - 1)).format())
      let tiemParams = new Date(new Date(new Date().setYear(value.split('年')[0])).setMonth(value.split('年')[1].split('月')[0] - 1))
      this.handleTimeParams(tiemParams)
    },
    handleTimeParams (dateTime) {
      let startMonthTime = dateTime.setDate(1) // 某月的第一天
      let endMonth = new Date()
      endMonth.setMonth(dateTime.getMonth() + 1)
      endMonth.setDate(0)
      let endMonthTime = endMonth.getTime() // 某月的最后一天
      let paramsObj = {
        studentSignupId: this.studentInfo.studentSignupId,
        studentId: this.studentInfo.studentId,
        schoolId: this.studentInfo.schoolId,
        startDate: startMonthTime < this.studentInfo.expiresStartTime ? this.studentInfo.expiresStartTime : startMonthTime,
        endDate: endMonthTime > this.studentInfo.expiresEndTime && !this.studentInfo.expiresInfo.includes('不限期') ? this.studentInfo.expiresEndTime : endMonthTime,
        scheduleType: this.isDisposeType
      }
      if (this.studentInfo.isClassCancelDispose === 1) {
        delete paramsObj.startDate
        delete paramsObj.endDate
        delete paramsObj.schoolId
        delete paramsObj.scheduleType
        api.disposeCourseList(paramsObj).then(res => { // 撤销销课课时
          this.disposeList = res.data
        })
      } else {
        api.unDisposeCourseList(paramsObj).then(res => { // 销课课时
          this.unDisposeList = res.data
        })
      }
    },
    handleSelected (value) { // 课程选择（学员入口）
      this.isSelected = true
      let paramsObj = {
        studentSignupId: value.studentSignupId,
        studentId: this.studentInfo.id,
        schoolId: value.schoolId
      }
      if (this.studentInfo.isCancelDispose === 1) {
        api.disposeCourseList(paramsObj).then(res => {
          this.disposeList = res.data
        })
      } else {
        api.unDisposeCourseList(paramsObj).then(res => {
          this.unDisposeList = res.data
        })
      }
    },
    handleSubmit () {
      let remainTotalTimes = this.studentInfo.times + this.studentInfo.donateTimes - this.studentInfo.usedDonateTimes - this.studentInfo.usedTimes
      if (this.isDispose && this.checkList.length > remainTotalTimes && this.studentInfo.times > 0) {
        this.$message.error('超过剩余次数，请重新选择')
      } else {
        if (this.isDispose) {
          let paramsUnDispose = {
            classId: this.studentInfo.classId,
            studentSignupId: this.studentInfo.isShowDispose ? this.selectedList.studentSignupId : this.studentInfo.studentSignupId,
            studentHistoryScheduleVOs: this.checkList,
            consumeType: this.isDisposeType
          }
          api.submitDispose(JSON.stringify(paramsUnDispose), {context: this}).then(res => {
            this.$emit('success').$emit('input', false)
          })
        } else {
          let paramsData = {
            studentSignupId: this.studentInfo.isShowDispose ? this.selectedList.studentSignupId : this.studentInfo.studentSignupId,
            scheduleIds: this.checkList
          }
          api.submitUnDispose(paramsData, {context: this}).then(res => {
            this.$emit('success').$emit('input', false)
          })
        }
      }
    }
  }
}
</script>

<style lang="scss">
  .dispose_course {
    .el-col{
      line-height:36px;
    }
    .selectedNum {
      margin: 20px 0 0
    }
    .vacade-scroll{
      max-height:450px;
      overflow-y: scroll;
    }
    .operator {
      max-width: 200px;
      display: inline-block;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      vertical-align: top;
    }
    .expiration_date {
      margin: 50px;
      font-size: 15px;
    }
  }
</style>
